import React from 'react';
import { connect } from 'react-redux';
import * as routerActions from 'react-router-redux';
import { Form, Input, Button, Select, message } from 'antd';
import Api from 'Utils/api';
import { GetLevel } from 'Constants/emergenceLevel';
import CommonBg from 'Page/DispatchPage/Components/CommonBorder';
import './index.scss';

const FormItem = Form.Item;
const { TextArea } = Input;
const Option = Select.Option;
class CreatePlan extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      selectTab: 1,
      isAdd: false,
      id: props.params.id,
      editRecord: '',
      eventLevelRecord: [],
    };
  }
  componentDidMount() {
    this.initForm();
    this.initEventLevel();
  }
  componentWillMount() {
    const { id } = this.state;
    if (!id) {
      this.setState({ isAdd: true });
    }
  }
  initForm() {
    const { id } = this.state;
    if (id) {
      const api = new Api({
        method: 'GET',
        path: `/schemas/${id}`,
        success: (json) => { this.setState({ editRecord: json }); },
        error: (msg) => {
          message.error(msg);
        }
      });
      api.run();
    }
  }
  initEventLevel() {
    const api = new Api({
      method: 'GET',
      path: '/emergencies',
      success: (json) => {
        this.setState({
          eventLevelRecord: json.data_list
        });
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  handCancel() {
    this.props.dispatch(routerActions.push('/system/dispatch/support/custom_plan'));
  }
  onEnter() {
    const { id } = this.state;
    const formValue = this.props.form.getFieldsValue();
    this.props.form.validateFieldsAndScroll((err) => {
      if (!err) {
        if (id) {
          const editApi = new Api({
            method: 'PATCH',
            path: `/schemas/${id}`,
            data: {
              title: formValue.title,
              event_level: formValue.event_level,
              operation_flow: formValue.operation_flow,
            },
            success: () => {
              this.props.dispatch(routerActions.push('/system/dispatch/support/custom_plan'));
            },
            error: (msg) => {
              message.error(msg);
            }
          });
          editApi.run();
        } else {
          const addApi = new Api({
            method: 'POST',
            path: '/schemas',
            data: {
              title: formValue.title,
              event_level: formValue.event_level,
              operation_flow: formValue.operation_flow,
            },
            success: () => {
              this.props.dispatch(routerActions.push('/system/dispatch/support/custom_plan'));
            },
            error: (msg) => {
              message.error(msg);
            }
          });
          addApi.run();
        }
      }
    });
  }
  render() {
    const title = this.state.isAdd ? '新增' : '修改';
    const { form } = this.props;
    const { getFieldDecorator } = form;
    const initialValue = this.state.editRecord ? { ...this.state.editRecord } : '';
    return (
      <div>
        <CommonBg
          title={`${title}预案`}
          content={
            <div className="create-plan-page">
              <div className="content-wrap">
                <div>
                  <Form layout={'horizontal'}>
                    <FormItem label="预案标题" >
                      {getFieldDecorator('title', {
                        initialValue: initialValue ? `${initialValue.title}` : '',
                        rules: [
                      { required: true, message: '请输入预案标题' }
                        ]
                      })(
                        <Input placeholder="请输入预案标题" style={{ width: 840 }} />
                      )}
                    </FormItem >
                    <FormItem label="事件等级" >
                      {getFieldDecorator('event_level', {
                        initialValue: initialValue ? initialValue.event_level.toString() : undefined,
                        rules: [
                      { required: true, message: '请选择事件等级' }
                        ]
                      })(
                        <Select placeholder="请选择指挥调度任务" style={{ width: 840 }}>
                          {
                            this.state.eventLevelRecord.map((item) => {
                              const levelObj = GetLevel(item.event_level);
                              return (<Option key={levelObj.id} value={levelObj.id.toString()}>{levelObj.name}</Option>);
                            })
                          }
                        </Select>
                      )}
                    </FormItem >
                    <FormItem label="业务流程" >

                      {getFieldDecorator('operation_flow', {
                        initialValue: initialValue ? `${initialValue.operation_flow}` : '',
                        rules: [
                          { required: true, message: '请输入业务流程' }
                        ]
                      })(
                        <TextArea placeholder="请输入业务流程" rows={4} style={{ width: 840, height: 150 }} />
                      )}
                    </FormItem >
                  </Form>
                </div>
                <div className="btns-wrap" style={{ marginTop: 100 }}>
                  <Button className="cancel-btn" onClick={this.handCancel.bind(this)}>取消</Button>
                  <Button className="ok-btn" onClick={this.onEnter.bind(this)}>确认</Button>
                </div>
              </div>
            </div>
        }
        />
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    ...state.routing
  };
}

export default Form.create()(connect(mapStateToProps)(CreatePlan));
